#!/bin/bash
set -e

cd $(dirname $0)/..

# This will start MySQL if needed.
if [ "${BOOTSTRAP_ON_RUN}" = "true" ]; then
    ./scripts/bootstrap
    trap "service mysql stop" EXIT SIGTERM
fi


RUNTIME_DIR=${RUNTIME_DIR:-./runtime/cli/}

if [ "${RUNTIME_DIR_CLEAN}" = "true" ]; then
    rm -rf $RUNTIME_DIR
fi

mkdir -p $RUNTIME_DIR

export JAVA_OPTS="
    -Xmx1024m
    -XX:+UseG1GC -XX:+UseStringDeduplication
    -Didempotent.checks=true
    -Ddb.cattle.database=h2
    -Dlogback.log.dir=$RUNTIME_DIR/logs/
    -Ddb.cattle.home=${RUNTIME_DIR}/db/"

CMD="./modules/main/build/install/cattle/bin/cattle"

if [ "$1" = "--background" ]; then
    rm -rf ${RUNTIME_DIR}/{run-success,run-error}
    $CMD --notify ./tools/development/run-success.sh --notify-error ./tools/development/run-error.sh &
    while sleep .5; do
        if [ -f ${RUNTIME_DIR}/run-success ]; then
            break
        elif [ -f ${RUNTIME_DIR}/run-error ]; then
            exit 1
        fi
    done
else
    $CMD
fi
